package cn.mengfly.testnrz.im.server.processer;

import cn.mengfly.testnrz.im.ProtoMsg;
import cn.mengfly.testnrz.im.client.ProtoInstant;
import cn.mengfly.testnrz.im.client.bean.User;
import cn.mengfly.testnrz.im.server.ServerSession;
import cn.mengfly.testnrz.im.server.SessionMap;
import cn.mengfly.testnrz.im.server.builder.LoginResponseBuilder;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author Mengfly
 */
public class LoginProcesser extends AbstractServerProcesser {

    static Map<String, String> userAndPassword = new HashMap<>();

    static {
        userAndPassword.put("admin", "admin");
        userAndPassword.put("u1", "p1");
        userAndPassword.put("u2", "p2");
        userAndPassword.put("u3", "p3");
    }

    private final LoginResponseBuilder loginResponseBuilder = new LoginResponseBuilder();

    @Override
    public ProtoMsg.HeadType type() {
        return ProtoMsg.HeadType.LOGIN_REQUEST;
    }

    @Override
    public boolean action(ServerSession session, ProtoMsg.Message proto) {
        ProtoMsg.LoginRequest loginRequest = proto.getLoginRequest();
        long seqNo = proto.getSequence();
        User user = User.fromMsg(loginRequest);

        // 检查用户
        boolean isValidUser = checkUser(user);
        if (!isValidUser) {
            ProtoInstant.ResultCodeEnum resultCode = ProtoInstant.ResultCodeEnum.NO_TOKEN;
            ProtoMsg.Message response = loginResponseBuilder.loginResponse(resultCode, seqNo, "-1");
            session.writeAndFlush(response);
            return false;
        }
        // 登录成功
        session.setUser(user);
        session.bind();
        ProtoInstant.ResultCodeEnum resultCode = ProtoInstant.ResultCodeEnum.SUCCESS;
        // 构造登录成功的报文
        ProtoMsg.Message response = loginResponseBuilder.loginResponse(resultCode, seqNo, session.getSessionId());
        session.writeAndFlush(response);
        return true;
    }

    public boolean checkUser(User user) {
        // 如果用户已经登录过了，不允许再次登录
        if (SessionMap.inst().hasLogin(user)) {
            return false;
        }
        if (userAndPassword.containsKey(user.getUid())) {
            return Objects.equals(userAndPassword.get(user.getUid()), user.getToken());
        }
        return false;
    }
}
